import { ensurePageOpen } from '../../utils.js';
import { BaseStrategy } from '../BaseStrategy.js';
import { platformConfig } from '../../config/index.js';
import fs from 'fs';
import { logInfo, logWarn, logError } from '../../logger.js';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import statisticsService from '../../services/statistics.js';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
export class PinduoduoStrategy extends BaseStrategy {
  constructor(context) {
    super(context, platformConfig.pinduoduo);
    this.context = context;
    this.baseUrl = platformConfig.pinduoduo.baseUrl;
  }

  async processRefunds(accountKey) {
    logInfo('[PinduoduoAutomation] 开始处理拼多多退款');
    let refundRecords = [];
    try {
      const page = await ensurePageOpen(this.context, this.baseUrl + '/aftersales/aftersale_list');
      this.pageLoad(page);
      await page.waitForTimeout(5000);
      await page.getByText('待商家处理', { exact: true }).click().catch(() => { logWarn('[PinduoduoAutomation] 点击待商家处理失败'); });
      await page.waitForTimeout(5000);
      const thtkbtn = page.locator('div[data-testid*="beast-core-tab-itemLabel"]').getByText('退货退款');
      const thtkbtnVisible = await thtkbtn.isVisible();
      if (thtkbtnVisible) {
        await thtkbtn.click();
        await page.waitForTimeout(5000);
      }
      let count = await page.locator('ul[data-testid="beast-core-pagination"] li').filter({ hasText: /共有*条*/ }).textContent();
      count = parseInt(count.match(/\d+/)[0]);
      logInfo(`[PinduoduoAutomation] 待处理退款订单数量: ${count}`);
      if (count > 10) {
        await page.locator('ul[data-testid="beast-core-pagination"] div[data-testid="beast-core-input"]').click();
        await page.waitForTimeout(500);
        await page.locator('div[data-testid="beast-core-portal"]').getByText('100').click();
        await page.waitForTimeout(5000);
      }
      await page.locator('div[data-testid="beast-core-select"] input[value="最近申请排序"]').click();
      await page.waitForTimeout(500);
      await page.getByText('临近逾期排序').click();
      await page.waitForTimeout(5000);
      const elements = await page.locator('div[class*="after-sales-table_order_item"]');
      const ele_count = await elements.count();
      logInfo(`[PinduoduoAutomation] 当前页面待处理订单数量: ${ele_count}`);
      await page.pause();
      // 这里假设有退款成功数据收集逻辑，收集到 refundRecords
      // 保存所有退款成功数据
      if (accountKey && refundRecords.length > 0) {
        statisticsService.saveRefundRecord(accountKey, refundRecords);
      }
      logInfo('[PinduoduoAutomation] 退款任务执行完成');
    } catch (err) {
      logError(`[PinduoduoAutomation] 退款任务异常: ${err.stack || err}`);
    }
  }

  async getShipmentInfo(shopName) {
    logInfo('[PinduoduoAutomation] 获取拼多多物流信息');
    const page = await ensurePageOpen(this.context, this.baseUrl + '/print/logistic-warning?quickfilter=c1');
    this.pageLoad(page);
    await page.waitForLoadState('networkidle').catch(() => { logWarn('等待网络空闲失败'); });
    await page.locator('svg[data-testid="beast-core-icon-close"]').click({ timeout: 2000 }).catch(() => { logWarn('关闭弹窗失败'); });
    const lsjjcs = await page.locator('div.item-option').filter({ hasText: '揽收即将超时' }).locator('span.item-option-num span').first().textContent().catch(() => { logWarn('获取揽收即将超时失败'); });
    logInfo(`[PinduoduoAutomation] 揽收即将超时：${lsjjcs}`);
    const lscs = await page.locator('div.item-option').filter({ hasText: '揽收已超时' }).locator('span.item-option-num span').first().textContent().catch(() => { logWarn('获取揽收已超时失败'); });
    logInfo(`[PinduoduoAutomation] 揽收已超时：${lscs}`);
    const lsgxcs = await page.locator('div.item-option').filter({ hasText: '揽收后待新已超时' }).locator('span.item-option-num span').first().textContent().catch(() => { logWarn('获取揽收后更新已超时失败'); });
    logInfo(`[PinduoduoAutomation] 揽收后更新已超时：${lsgxcs}`);
    return {
      '店铺名称': shopName || '拼多多',
      '揽收即将超时': lsjjcs,
      '揽收已超时': lscs,
      '揽收后更新已超时': lsgxcs
    };
  }

  async getExchangePendingCount() {
    const page = await ensurePageOpen(this.context, this.baseUrl + '/aftersales/exchange-list');
    await page.waitForTimeout(5000);
    await closePopups(page);
    await page.getByText('待商家处理', { exact: true }).click().catch(() => { logWarn('[PinduoduoAutomation] 点击待商家处理失败'); });
    await page.waitForTimeout(5000);
    const hh = page.locator('div[data-testid*="beast-core-tab-itemLabel"]').getByText('换货');
    const hhVisible = await hh.isVisible();
    let count = 0;
    if (hhVisible) {
      // 获取hh文字中的数字
      count = await hh.textContent().match(/\d+/)[0];
    }
    logInfo(`[PinduoduoAutomation] 换货待处理订单数: ${count}`);
    return count;
  }
  async test() {
    const page = await ensurePageOpen(this.context, this.baseUrl + '/aftersales/aftersale_list');
    this.pageLoad(page);
    await page.pause();
  }
}